package com.adam.masterSpringMVC4.config;

import com.adam.masterSpringMVC4.profile.UserProfileSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserProfileSession userProfileSession;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();
        if(username.equals("admin")) {
            userProfileSession.setLoginType(UserProfileSession.LoginType.Admin);
        } else {
            userProfileSession.setLoginType(UserProfileSession.LoginType.User);
        }
        System.out.println("User:" + username + "login success");
        response.sendRedirect("/profile");
    }

}
